//
//  CourseDetailsViewController.m
//  ZFPlayer_Example
//
//  Created by 洪欣 on 2019/1/4.
//  Copyright © 2019年 紫枫. All rights reserved.
//

#import "CourseDetailsViewController.h"
#import "CourseDetailsIntroduceView.h"
#import "CourseDetailsCatalogView.h"
#import "WYHXNetWorkManager.h"
#import "CourseDetailsModel.h"
#import <YYModel.h>
#import "CourseDetailsLecturerView.h"
#import "LBKeshDetailVC.h"
#import "LBKeshDetailsVC.h"
@interface CourseDetailsViewController ()
@property (weak, nonatomic) IBOutlet UIScrollView *scrollView;
@property (weak, nonatomic) IBOutlet CourseDetailsIntroduceView *introduceView;
@property (weak, nonatomic) IBOutlet CourseDetailsCatalogView *catalogView;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *lecturerViewHeight;
@property (weak, nonatomic) IBOutlet UIView *lecturerView;
@property (strong, nonatomic) NSMutableArray *lecturerViews;
@property (weak, nonatomic) IBOutlet UIView *bottomView;

@property (weak, nonatomic) IBOutlet UIButton *ShoppingBtn;/**购买按钮*/
@property (weak, nonatomic) IBOutlet UILabel *priceLab;/**价格*/
@property (nonatomic ,strong) CourseDetailsModel *model;
@property (weak, nonatomic) IBOutlet UIButton *collectBtn;/**收藏按钮*/
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *bottomViewConstriants;/**底部控件constraint*/
@property (weak, nonatomic) IBOutlet UILabel *courseJieshaoLab;
@property (weak, nonatomic) IBOutlet UILabel *kechengjieshaoLab;
@property (weak, nonatomic) IBOutlet UIButton *palyBtn;
@property (weak, nonatomic) IBOutlet UILabel *jiLab;
@property (weak, nonatomic) IBOutlet UILabel *contentLab;
@property (nonatomic,assign)CGFloat currenttime;
@property (nonatomic, strong) NSString  *hourId;//当前课程id
@property (strong, nonatomic)  NSString *publicThumString;/**当前点击的视频或者音频的url*/
@property (weak, nonatomic) IBOutlet UILabel *jiangshijieLab;
@property (nonatomic, strong) CourseDetailsDataModel *dataIspayModel;

@end

@implementation CourseDetailsViewController
#pragma mark 立即购买
- (IBAction)clickShoppingBtn:(id)sender {
    NSString *token = [UserModel getUserModel].token;
    if (!token) {
        LBLoginVC *loginVC = [[LBLoginVC alloc] init];
        loginVC.jumpType = @"1";
        [self.navigationController pushViewController:loginVC animated:YES];
    }else{
#pragma mark支付
        NSString *isVisitor = [UserModel getUserModel].isVisitor;
        if ([isVisitor isEqualToString:@"1"]) {
            [self alertController];
        }else{
            [self gotoShopping];
        }
    }
}

- (void)gotoShopping{
    LBPayVC *payVC = [LBPayVC new];
    payVC.type = @"2";//课程包跳转 支付页面 2
    payVC.name = self.model.data.packName;
    payVC.price = self.model.data.packagePrice;
    payVC.courserId = self.model.data.packId;
    [self.navigationController pushViewController:payVC animated:YES];
}
- (void)alertController{
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"请选择登录后购买，在其他设备也可以观看" message:nil preferredStyle:UIAlertControllerStyleAlert];
    [alertController addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
    }]];
    [alertController addAction:[UIAlertAction actionWithTitle:@"登录" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        LBLoginVC *loginVC = [[LBLoginVC alloc] init];
        loginVC.jumpType = @"1";
        [self.navigationController pushViewController:loginVC animated:YES];
    }]];
    [alertController addAction:[UIAlertAction actionWithTitle:@"游客模式购买(仅限本设备观看)" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        [self gotoShopping];
    }]];
    
    //推出控制器
    [self presentViewController:alertController animated:YES completion:nil];
}
- (IBAction)clickCollectBtn:(id)sender {
    NSString *token = [UserModel getUserModel].token;
    if (token.length==0||!token) {
        LBLoginVC *vc = [[LBLoginVC alloc] init];
        [self.navigationController pushViewController:vc animated:YES];
        
    }else{

        
        //调用取消或者收藏
        NSMutableDictionary *data = [NSMutableDictionary dictionary];
        [data setObject:token forKey:@"token"];//通用参数
        NSString *str = [NSString stringWithFormat:@"%ld",(long)self.model.data.isCollect];
        if ([str isEqualToString:@"1"]) {
            [data setObject:self.packId forKey:@"courseId"];
            [data setObject:self.collectType forKey:@"courseType"];//区分课程包还是 或者免费课程

            [WYHXNetWorkManager post:WKCancelCoureseCellect_WKURL params:data completionHandler:^(id responseObj, NSError *error) {
                NSString *code = responseObj[@"code"];
                NSString *msg = responseObj[@"msg"];
//                NSLog(@"%@",responseObj);
                if (code.integerValue==200) {
                    [MBProgressHUD showSuccess:msg toView:self.view];
                    [sender setTitle:@"收藏" forState:UIControlStateNormal];
                    [self loadData];
                }
            }];
    
        }else{
            
            [data setObject:self.packId forKey:@"courseId"];
            [data setObject:self.collectType forKey:@"collectType"];//区分课程包还是 或者免费课程
            
            [WYHXNetWorkManager post:WKCoureseCellect_WKURL params:data completionHandler:^(id responseObj, NSError *error) {
                NSString *code = responseObj[@"code"];
                NSString *msg = responseObj[@"msg"];
//                NSLog(@"%@",responseObj);
                if (code.integerValue==200) {
                    
                    [MBProgressHUD showSuccess:msg toView:self.view];
                    [sender setTitle:@"已收藏" forState:UIControlStateNormal];
                    [self loadData];
                }

            }];
        }
        
    }
}
- (void)loadData {
    self.palyBtn.hidden = YES;
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    dict[@"packId"] = self.packId;
    NSString *token = [UserModel getUserModel].token;
    if (token) {
        dict[@"canNullToken"] = token;
    }
    
    __weak typeof(self) weakSelf = self;
    
    [WYHXNetWorkManager get:WKCoursePackDetail_WKURL params:dict completionHandler:^(id responseObj, NSError *error) {
        if (!error) {
            CourseDetailsModel *model = [CourseDetailsModel yy_modelWithDictionary:responseObj];
            self.model = model;
//            NSLog(@"%@",model);
            weakSelf.introduceView.model = model.data;
//            CourseDetailsDataModel
            self.dataIspayModel = model.data;
            weakSelf.catalogView.model = model.data;
            self.introduceView.model2 = self.model;
            self.priceLab.text =[NSString stringWithFormat:@"¥%@", self.model.data.packagePrice];
            self.contentLab.text = model.data.packagePresent;
            self.jiLab.text = model.data.packTitle;
            self.palyBtn.hidden = YES;

            [self.introduceView.controlView.portraitControlView.bgImageView sd_setImageWithURL:[NSURL URLWithString:self.publicThumString] placeholderImage:[UIImage imageNamed:@"wk_list_bgimg"]];
            [self.introduceView.controlView.landScapeControlView.bgImageView sd_setImageWithURL:[NSURL URLWithString:self.publicThumString] placeholderImage:[UIImage imageNamed:@"wk_list_bgimg"]];
            if (model.data.isCollect ==1) {
                [self.collectBtn setTitle:@"已收藏" forState:UIControlStateNormal];
            }else{
                 [self.collectBtn setTitle:@"收藏" forState:UIControlStateNormal];
            }
            if ([model.data.isPay integerValue]==1) {//ispay 1 支付完成
                self.bottomView.hidden = YES;
                self.bottomViewConstriants.constant = 0;
            }else{
                self.bottomView.hidden = NO;
                self.bottomViewConstriants.constant = 44;
            }
            [weakSelf loadLecturerData];
        }
    }];
}
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    [self loadData];
    self.introduceView.player.viewControllerDisappear = NO;
    [self.navigationController.navigationBar setTitleTextAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:16],NSForegroundColorAttributeName:[UIColor blackColor]}];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    self.introduceView.player.viewControllerDisappear = YES;
    if (self.hourId) {
        [self getplaylenth];
    }
}

- (void)getplaylenth{
    
    
    NSString *time = [NSString stringWithFormat:@"%.f",self.introduceView.player.currentPlayerManager.currentTime];
    NSInteger index = [time integerValue];
//    NSLog(@"%f",[time floatValue]);
    
    NSString *token = [UserModel getUserModel].token;
    if (!token) {
        
    }else{
        NSMutableDictionary *param = [NSMutableDictionary dictionary];
        [param setObject:self.hourId forKey:@"hourId"];
        [param setObject:self.packId forKey:@"courseId"];
        [param setObject:@(index) forKey:@"videoLength"];
        [param setObject:token forKey:@"token"];
        
        //传递给服务器最后播放的时长
        [WYHXNetWorkManager post:WKGetUserStudyrecod_WKURL params:param completionHandler:^(id responseObj, NSError *error) {
            //        NSLog(@"%@%@",responseObj,error);
        }];
    }

    
}
#pragma mark- 课程包分享成功后 获取积分接口
- (void)senWeChatShareSuccess{
    
    NSMutableDictionary *data = [NSMutableDictionary dictionary];
    NSString *token = [UserModel getUserModel].token;
    [data setObject:token forKey:@"token"];
    [data setObject:self.packId forKey:@"courseId"];
    [data setObject:@"2" forKey:@"courseType"];
    [WYHXNetWorkManager post:WKQshareCourseData_WKURL params:data completionHandler:^(id responseObj, NSError *error) {
        NSString *code = responseObj[@"code"];
        NSString *msg = responseObj[@"msg"];
        if ([code integerValue]==200) {
//            NSLog(@"%@",responseObj);
            NSString *data = responseObj[@"data"];
            [MBProgressHUD showSuccess:msg toView:self.view];
            return ;
        }
    }];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(senWeChatShareSuccess) name:@"WeChatShareSuccess" object:nil];
    self.jiangshijieLab.textColor = rgb(51,51,51);
    self.jiangshijieLab.font = [UIFont systemFontOfSize:15];

    self.navigationItem.title = @"课程包详情";
    self.palyBtn.hidden = YES;
    //课程介绍文本颜色
    self.kechengjieshaoLab.textColor = rgb(51, 51, 51);
    [self setupcCourseAttributedText];
    @weakify(self)
    self.introduceView.player.orientationWillChange = ^(ZFPlayerController * _Nonnull player, BOOL isFullScreen) {
        @strongify(self)
        [self setNeedsStatusBarAppearanceUpdate]; 
    };
    
    self.introduceView.player.playerDidToEnd = ^(id  _Nonnull asset) {
        @strongify(self)
//        [self.introduceView.player.currentPlayerManager replay];
//        [self.controlView resetControlView];
        [self.introduceView.player.currentPlayerManager seekToTime:0 completionHandler:nil];
    };
    __weak typeof(self) weakSelf = self;
    self.catalogView.selectTableViewCellBlock = ^(CourseDetailsCourseHourOutputDTODataModel * _Nonnull model) {
        //赋值后
        self.hourId = model.hourId;

        if ([self.dataIspayModel.isPay isEqualToString:@"0"]) {
            [MBProgressHUD showSuccess:@"请先兑换此课程" toView:self.view];
            return;
        }
        NSString *URLString = [NSString stringWithFormat:@"%@%@",Public_URL,model.hourUrl];
        NSString *encodeUrlString = [URLString stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
        NSString *thumUrl = [NSString stringWithFormat:@"%@%@",Public_URL,model.videoImage];
        self.publicThumString = thumUrl;
//        NSLog(@"%@",URLString);
        self.publicThumString = thumUrl;
        self.introduceView.controlView.portraitControlView.bgImageView.hidden = NO;
        if (thumUrl) {
            [self.introduceView.controlView.portraitControlView.bgImageView sd_setImageWithURL:[NSURL URLWithString:thumUrl] placeholderImage:[UIImage imageNamed:@"default_cover"]];
            [self.introduceView.controlView.landScapeControlView.bgImageView sd_setImageWithURL:[NSURL URLWithString:thumUrl] placeholderImage:[UIImage imageNamed:@"default_cover"]];
        }
        
        self.introduceView.player.assetURL = [NSURL URLWithString:encodeUrlString];
//        [self.introduceView.player.currentPlayerManager play];
        NSLog(@"正在播放的课程 - %@",model);
        if ([self.model.data.isPay integerValue]==0) {
            [MBProgressHUD showSuccess:@"请先兑换此课程" toView:self.view];
            return ;
        }
        
        weakSelf.introduceView.currentSubModel = model;
        
        if (model.hourType.integerValue == 2) {//图片

            [self.introduceView.player.currentPlayerManager pause];
            LBKeshDetailsVC *keshiVC = [[LBKeshDetailsVC alloc] init];
            keshiVC.htmlString = model.hourInfo;
            [self.navigationController pushViewController:keshiVC animated:YES];
            

        }else{
            
            if (model.hourType.integerValue==1) {
                    self.introduceView.controlView.portraitControlView.bgImageView.hidden = NO;
                }else{
                    self.introduceView.controlView.portraitControlView.bgImageView.hidden = YES;
                    self.introduceView.controlView.landScapeControlView.bgImageView.hidden = YES;
                }
            NSString *URLString = [NSString stringWithFormat:@"%@%@",Public_URL,model.hourUrl];
            NSString *encodeUrlString = [URLString stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
//            NSLog(@"%@",URLString);
            
            NSMutableDictionary *dict = [NSMutableDictionary dictionary];
            NSString *token = [UserModel getUserModel].token;
            [dict setObject:model.hourId forKey:@"hourId"];
            [dict setObject:token forKey:@"token"];
            __weak typeof(self)weakself = self;
            //获取用户观看视频或者音频最后一次时长
            [WYHXNetWorkManager get:WKGetUserLookvideoaudioLeng_WKURL params:dict completionHandler:^(id responseObj, NSError *error) {
                NSString *code = responseObj[@"code"];
                if ([code integerValue]==200) {
                    NSString *length = responseObj[@"data"];
                    NSInteger index = [length integerValue];
                    self.introduceView.player.currentPlayerManager.seekTime = index;
                }
                
            }];
            self.introduceView.player.assetURL = [NSURL URLWithString:encodeUrlString];
            [self.introduceView.player.currentPlayerManager play];
            [weakSelf loadLecturerData];
        }
        
        [self.introduceView.controlView.portraitControlView.playOrPauseBtn addTarget:self action:@selector(clickbtn:) forControlEvents:UIControlEventTouchUpInside];
        
    }; 
    

    //设置导航
    [self setupNavigationBar];
    

}
#pragma mark - 点击播放/暂停按钮后恢复播放速度
- (void)clickbtn:(UIButton *)sender{
    self.introduceView.player.currentPlayerManager.rate = 1.0;
}
- (void)setupNavigationBar{
    UIButton *btn = [[UIButton alloc] init];
    [btn addTarget:self action:@selector(clickRightItemBtn:) forControlEvents:UIControlEventTouchUpInside];
    [btn setImage:LBImage(@"wk_share") forState:UIControlStateNormal];
    btn.frame = CGRectMake(0, 0, 30, 30);
    UIBarButtonItem *rightItem = [[UIBarButtonItem alloc] initWithCustomView:btn];
    self.navigationItem.rightBarButtonItem = rightItem;
}

- (void)BackAction{
    [self.navigationController popViewControllerAnimated:YES];
}


#pragma mark - 处理底部视图高度
- (void)loadLecturerData {
    
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    dict[@"refId"] = self.packId;
    dict[@"type"] = self.collectType;
    __weak typeof(self) weakSelf = self;
    //http://47.95.9.40/vlearn/CourseTeacherController/queryTeacherByCourseId
    //http://47.95.5.203/CourseTeacherController/queryTeacherByCourseId
//    讲师详情
    [WYHXNetWorkManager get:WKTeacherDetail_WKURL params:dict completionHandler:^(id responseObj, NSError *error) {
        if (!error) {
            for (UIView *view in weakSelf.lecturerViews) {
//                [view removeFromSuperview];
            }
            CourseDetailsLecturerModel *model = [CourseDetailsLecturerModel yy_modelWithDictionary:responseObj];
            weakSelf.lecturerViews = @[].mutableCopy;
            NSInteger i = 0;
            CGFloat bottomMargin = 0;
            if (model.data.count>0) {
                self.jiangshijieLab.hidden = YES;
                for (CourseDetailsLecturerDataModel *subModel in model.data) {
                    CourseDetailsLecturerView *view = [CourseDetailsLecturerView initView];
                    view.frame = CGRectMake(0, bottomMargin, weakSelf.view.frame.size.width, 0);
                    view.index = i;
                    view.model = subModel;
                    i++;
                    [weakSelf.lecturerView addSubview:view];
                    [weakSelf.lecturerViews addObject:view];
                    bottomMargin = CGRectGetMaxY(view.frame) + 0.5f;
                    if (i == model.data.count - 1) {
                        bottomMargin = CGRectGetMaxY(view.frame);
                    }
                }
                [UIView animateWithDuration:0.25 animations:^{
                    weakSelf.lecturerViewHeight.constant = bottomMargin;
                    [weakSelf.view layoutIfNeeded];
                }];
            }else{

                self.jiangshijieLab.hidden = NO;
//                [UIView animateWithDuration:0.25 animations:^{
                    self.lecturerViewHeight.constant = 50;
//                    [weakSelf.view layoutIfNeeded];
//                }];
            }

        }
    }];
}




//- (BOOL)shouldAutorotate {
//    /// 如果只是支持iOS9+ 那直接return NO即可，这里为了适配iOS8
//    return self.introduceView.player.shouldAutorotate;
//}
//
//- (UIStatusBarAnimation)preferredStatusBarUpdateAnimation {
//    return UIStatusBarAnimationSlide;
//}
//
//- (UIInterfaceOrientationMask)supportedInterfaceOrientations {
//    if (self.introduceView.player.isFullScreen) {
//        return UIInterfaceOrientationMaskLandscape;
//    }
//    return UIInterfaceOrientationMaskPortrait;
//}
//
//- (UIStatusBarStyle)preferredStatusBarStyle {
//    if (self.introduceView.player.isFullScreen) {
//        return UIStatusBarStyleLightContent;
//    }
//    return UIStatusBarStyleDefault;
//}
//
//- (BOOL)prefersStatusBarHidden {
//    return self.introduceView.player.isStatusBarHidden;
//}
- (void)setupcCourseAttributedText{
    NSString *str = @"<span style=\"font-size:16px;\"><span style=\"font-size:20px;\"><span style=\"color:#0079FE;\">心安，幸福<\/span><\/span><\/span><\/b><\/p>\n<br>\n<p><b><span style=\"font-size:20px;\"><span style=\"color:#0079FE;\"><span style=\"font-size:16px;\"><img src=\"https:\/\/file.dev.91xiangke.com\/user\/upload\/1e6b74c6d2a44b7582bb95f3b64e8ff2\/ee53130d-6429-426b-92f3-49959c3936951532313418546-880x568.jpg\" \/><\/span><\/span><\/span><\/b><\/p>\n<p style=\"text-align:start;\"><b><span style=\"font-size:20px;\"><span style=\"color:#0079FE;\"><span style=\"font-size:16px;\">​<\/span><\/span><\/span><\/b><\/p>\n<p><b><span style=\"font-size:16px;\">秋雨丝丝洒枝头<\/span><\/b><\/p>\n<p><b><span style=\"font-size:16px;\">烟缕织成愁<\/span><\/b><\/p>\n<p><b><span style=\"font-size:16px;\">遥望落花满地残红<\/span><\/b><\/p>\n<p><b><span style=\"font-size:16px;\">曾也枝头盈盈娉婷<\/span><\/b><\/p>\n<p><b><span style=\"font-size:16px;\">装饰他人梦<\/span><\/b><\/p>\n<br>\n<p><b><span style=\"color:#009FB8;\"><span style=\"font-size:18px;\"><u>如今花落簌簌<\/u><\/span><\/span><\/b><\/p>\n<p><b><span style=\"color:#009FB8;\"><span style=\"font-size:18px;\"><u>曾绚烂完美刹那芳华<\/u><\/span><\/span><\/b><\/p>\n<br>\n<p><b><span style=\"font-size:16px;\">看那花瓣上的珍珠<\/span><\/b><\/p>\n<p><b><span style=\"font-size:16px;\">不甚清风的摆动<\/span><\/b><\/p>\n<p><b><span style=\"font-size:16px;\">悄然滑落<\/span><\/b><\/p>\n<p><b><span style=\"font-size:16px;\">那不舍的是离愁<\/span><\/b><\/p>\n<p><b><span style=\"font-size:16px;\"><i>尘缘已过<\/i><\/span><\/b><\/p>\n<p><b><span style=\"font-size:16px;\"><i>聚散匆匆<\/i><\/span><\/b><\/p>\n<br>\n<p><b><img src=\"https:\/\/file.dev.91xiangke.com\/user\/upload\/1e6b74c6d2a44b7582bb95f3b64e8ff2\/3348048b-c276-40f7-a98f-89cce95168c51532313469210-880x578.jpg\" \/><span style=\"font-size:18px;\"><span style=\"color:#009FB8;\"><\/span><\/span><\/b><\/p>\n<p style=\"text-align:start;\"><b><span style=\"font-size:18px;\"><span style=\"color:#009FB8;\">​<\/span><\/span><\/b><\/p>\n<p><b><span style=\"font-size:16px;\">不需忧伤<\/span><\/b><\/p>\n<p><b><span style=\"font-size:16px;\">花儿<\/span><\/b><\/p>\n<p><b><span style=\"font-size:16px;\">不会因为离枝而失去芬芳<\/span><\/b><\/p>\n<p><b><span style=\"font-size:16px;\">草儿<\/span><\/b><\/p>\n<p><b><span style=\"font-size:16px;\">不会因为寒冬而放下生的期望<\/span><\/b><\/p>\n<br>\n<p><b><span style=\"font-size:16px;\">今年花胜去年红<\/span><\/b><\/p>\n<p><b><span style=\"font-size:16px;\">明年花更好<\/span><\/b><\/p>\n<p><b><span style=\"font-size:16px;\">花开最美<\/span><\/b><\/p>\n<p><b><span style=\"font-size:16px;\">不负这红尘人间<\/span><\/b><\/p>\n<br>\n<p><b><img src=\"https:\/\/file.dev.91xiangke.com\/user\/upload\/1e6b74c6d2a44b7582bb95f3b64e8ff2\/80429d91-902a-403d-897c-500fb0028ab01532313480214-880x616.jpg\" \/><span style=\"font-size:18px;\"><span style=\"color:#009FB8;\"><\/span><\/span><\/b><\/p>\n<p style=\"text-align:start;\"><b><span style=\"font-size:18px;\"><span style=\"color:#009FB8;\">​<\/span><\/span><\/b><\/p>\n<br>\n<p><b><span style=\"font-size:16px;\">　　细数走过的岁月，欢乐伴着忧伤。在时光的深处中，最美的永远艳丽多彩不褪色，那些伤痛，时间久了也就模糊不清，留下的记忆也是残缺碎片。遇到不满意时，总会拿过去的好作比较，留恋过去，厌恶此刻，始不知过去也是此刻，此刻也会过去。行走红尘人间，做个随遇而安的草木女子，让清风拂袖，心香暖怀。生命的旅途，总会有千回百转满意时，总会拿过去的好作比较，留恋过去，厌恶此刻，始不知过去也是此刻，此刻也会过去。行走红尘人间，做个随遇而安的草木女子，让清风拂袖，心香暖怀。生命的旅途，总会有千回百转\357\274，悲喜寒凉，季节的辗转，绮丽的风景。若是懂得，这都是生活赋予的完美。有些人，有些事，也许进了你的眼，滑过你的心，又悄然的溜走了，也许只为相遇，留一道风景。把路途的美景丰盈心灵，化一道属于自己的风情。<\/span>";
    
    
    //以下内容是处理富文本的代码
    __block NSMutableAttributedString * attrString;
    
    //异步处理富文本 -->主要因为内容太多，比较耗时
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        attrString = [[NSMutableAttributedString alloc] initWithData:[self.courseInfo dataUsingEncoding:NSUnicodeStringEncoding] options:@{NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType} documentAttributes:nil error:nil];
        
        [attrString addAttributes:@{NSBaselineOffsetAttributeName: @(5),
                                    NSFontAttributeName:[UIFont systemFontOfSize:14]} range:NSMakeRange(0, attrString.length)];
        //处理完以后赋值
        dispatch_async(dispatch_get_main_queue(), ^{
            self.courseJieshaoLab.attributedText = attrString;
        });
    });
    
}
- (void)jumpLloginviewController{
    LBLoginVC *loginVC = [[LBLoginVC alloc] init];
    loginVC.jumpType = @"1";
    [self.navigationController pushViewController:loginVC animated:YES];
}
#pragma mark - 点击分享
- (void)clickRightItemBtn:(UIButton *)sender{
    
    NSString *token = [UserModel getUserModel].token;
    if (!token||token.length==0) {
        [self jumpLloginviewController];
    }else{
        [LWShareService shared].shareBtnClickBlock = ^(NSIndexPath *index) {
            NSInteger tag = index.row;
            [[LWShareService shared] hideSheetView];
            NSString *url = [NSString stringWithFormat:@"%@%@&userId=%@",WKPackCourseShare_url,self.model.data.packId,[UserModel getUserModel].token];
            //        NSLog(@"%@",url);
            NSString *shareUrl = url;//[NSString stringWithFormat:@"%@%@",WKPackCourseShare_url,self.model.data.packId];
            switch (tag) {
                case 0:
                {
                    
                    
                    WXWebpageObject *webpageObject = [WXWebpageObject object];
                    webpageObject.webpageUrl = shareUrl;
                    
                    WXMediaMessage *message = [WXMediaMessage message];
                    message.title = self.model.data.packTitle;
                    message.description = self.model.data.packageInfo;
                    //                [message setThumbImage:[UIImage imageNamed:self.model.data.imgUrl]];
//                    NSString *URLString = [NSString stringWithFormat:@"%@%@",Public_URL,self.model.data.videoImage];
//                    UIImage *image = [self getImageFromURL:URLString];
//
//                    [message setThumbData:[self imageWithImage:image scaledToSize:CGSizeMake(300, 300)]];
                    [message setThumbImage:[UIImage imageNamed:@"wanke_logo"]];
                    message.mediaObject = webpageObject;
                    SendMessageToWXReq *req = [[SendMessageToWXReq alloc] init];
                    req.bText = NO;
                    req.message = message;
                    req.scene = WXSceneSession;
                    [WXApi sendReq:req];
                }
                    break;
                case 1:
                {
                    WXWebpageObject *webpageObject = [WXWebpageObject object];
                    webpageObject.webpageUrl = shareUrl;
                    
                    WXMediaMessage *message = [WXMediaMessage message];
                    message.title = self.model.data.packTitle;
                    message.description = self.model.data.packageInfo;
                    //                [message setThumbImage:[UIImage imageNamed:self.model.data.imgUrl]];
//                    NSString *URLString = [NSString stringWithFormat:@"%@%@",Public_URL,self.model.data.videoImage];
//                    UIImage *image = [self getImageFromURL:URLString];
//
//                    [message setThumbData:[self imageWithImage:image scaledToSize:CGSizeMake(300, 300)]];
                    [message setThumbImage:[UIImage imageNamed:@"wanke_logo"]];
                    message.mediaObject = webpageObject;
                    
                    SendMessageToWXReq *req = [[SendMessageToWXReq alloc] init];
                    req.bText = NO;
                    req.message = message;
                    req.scene = WXSceneTimeline;
                    [WXApi sendReq:req];
                    
                }
                    break;
                default:
                    break;
            }
        };
        [[LWShareService shared] showInViewController:self];
    }
}
- (NSData *)imageWithImage:(UIImage*)image scaledToSize:(CGSize)newSize;
{
    UIGraphicsBeginImageContext(newSize);
    [image drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];
    UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return UIImageJPEGRepresentation(newImage, 0.8);
}
-(UIImage *) getImageFromURL:(NSString *)fileURL
{
    UIImage * result;
    NSData * data = [NSData dataWithContentsOfURL:[NSURL URLWithString:fileURL]];
    result = [UIImage imageWithData:data];
    return result;
}
@end
